package org.diysearch.dao.impls;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.diysearch.dao.interfaces.SearchEngineDao;
import org.diysearch.models.Link;
import org.diysearch.models.SearchResult;
import org.diysearch.tools.BaseTool;

public class SearchEngineDaoImpl implements SearchEngineDao {
	private static final Log LOG = LogFactory.getLog(SearchEngineDaoImpl.class);
	@Override
	public SearchResult search(String query) throws Exception {
		
		SolrQuery sq = new SolrQuery();
		sq.setQuery(query);
		sq.setFacet(true);
		sq.setFacetMinCount(1);
		sq.setFacetLimit(8);
		sq.addFacetField("category");
		sq.addFacetField("tags");
		sq.setIncludeScore(true);
		QueryResponse rsp = BaseTool.SOLR_SERVER.query(sq);

		SolrDocumentList sdl = rsp.getResults();
		List<Link> results = rsp.getBeans(Link.class);
		
		SearchResult sr = new SearchResult();

		FacetField tagsFacet = rsp.getFacetField("tags");
		FacetField catsFacet = rsp.getFacetField("category");
		
		List<String> facets = new ArrayList<String>();
		for (FacetField.Count count : tagsFacet.getValues()) {
			StringBuilder sb = new StringBuilder();
			sb.append("t:").append(count.getName()).append(":").append(count.getCount());
			facets.add(sb.toString());
		}
		
		
		for (FacetField.Count count : catsFacet.getValues()) {
			StringBuilder sb = new StringBuilder();
			sb.append("c:").append(count.getName()).append(":").append(count.getCount());
			facets.add(sb.toString());
		}
		
		sr.setFacets(facets.toArray());
		sr.setMaxScore(sdl.getMaxScore());
		sr.setHits(sdl.getNumFound());
		
		Iterator<SolrDocument> i = sdl.iterator();
		List<Link> links = new ArrayList<Link>();
		while (i.hasNext()) {
			SolrDocument sd = i.next();
			float score = Float.parseFloat(sd.getFieldValue("score").toString());
			String url = String.valueOf(sd.getFieldValue("url"));
			
			for (Link l : results) {
				if (url.equals(l.getUrl())) {
					l.setScore(score);
					links.add(l);
				}
			}
		}
		
		sr.setLinks(links);

		return sr;
	}

}
